/*******************************************************************
 * Title: deskey.sc
 * Author: Brian Peck
 * Date: Spring 2011
 * Description: Specification model for DES key generator
 *******************************************************************/

import "i_sender";
import "i_receiver";
import "des.h";

behavior deskey(i_receiver ir, i_sender is) 
{
  void main(void) {
    unsigned char *key;
    short edf;
    int i,j,l,m,n;
    unsigned char pclm[56], pcr[56];
    unsigned long kn[32];
    while (1) {
      ir.receive(&key, sizeof(key));
      ir.receive(&edf, sizeof(edf));
      
      // Generate DES key schedule
      register int i, j, l, m, n;
      unsigned char pc1m[56], pcr[56];
      unsigned long kn[32];

      for ( j = 0; j < 56; j++ ) {
        l = pc1[j];
        m = l & 07;
        pc1m[j] = (key[l >> 3] & bytebit[m]) ? 1 : 0;
      }
      for( i = 0; i < 16; i++ ) {
        if( edf == DE1 ) m = (15 - i) << 1;
        else m = i << 1;
        n = m + 1;
        kn[m] = kn[n] = 0L;
        for( j = 0; j < 28; j++ ) {
          l = j + totrot[i];
          if( l < 28 ) pcr[j] = pc1m[l];
          else pcr[j] = pc1m[l - 28];
        }
        for( j = 28; j < 56; j++ ) {
          l = j + totrot[i];
          if( l < 56 ) pcr[j] = pc1m[l];
          else pcr[j] = pc1m[l - 28];
        }
        for( j = 0; j < 24; j++ ) {
          if( pcr[pc2[j]] ) kn[m] |= bigbyte[j];
          if( pcr[pc2[j+24]] ) kn[n] |= bigbyte[j];
        }
      } // end for i
      cookey(kn);
//      is.send(&kn, sizeof(kn));
    } // end while
  } // end main

  void cookey(unsigned long *raw1) {
    unsigned long *cook, *raw0;
    unsigned long dough[32];
    int i;
    cook = dough;
    for( i = 0; i < 16; i++, raw1++ ) {
      raw0 = raw1++;
      *cook    = (*raw0 & 0x00fc0000L) << 6;
      *cook   |= (*raw0 & 0x00000fc0L) << 10;
      *cook   |= (*raw1 & 0x00fc0000L) >> 10;
      *cook++ |= (*raw1 & 0x00000fc0L) >> 6;
      *cook    = (*raw0 & 0x0003f000L) << 12;
      *cook   |= (*raw0 & 0x0000003fL) << 16;
      *cook   |= (*raw1 & 0x0003f000L) >> 4;
      *cook++ |= (*raw1 & 0x0000003fL);
    } // end for i
    is.send(&dough, sizeof(dough));
  } // end cookey

} // end behavior deskey
